package lg.iu.transforms;

import lg.iu.ClassHooks;
import lg.iu.FieldHooks;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;

import wolf.iu.framework.ClassContainer;
import wolf.iu.framework.ClassesHandler;
import wolf.iu.framework.HooksList;
import wolf.iu.framework.hooks.AbstractClassHookEnum;
import wolf.iu.framework.hooks.DependencyTransform;
import wolf.iu.framework.hooks.HookState;

public class AnimableListTransform extends DependencyTransform {

    @Override
    public HookState execute(final ClassesHandler ch, final ClassContainer cc,
            final HooksList hooks) {
        
        final String aName = hooks.getHook(ClassHooks.Animable).getFullOldName();
        
        if (!containsField(cc, "L" + aName + ";") || !containsField(cc, "L" + cc.getName() + ";") || aName.equals(cc.getName()))
            return HookState.WrongClass;
        
        hooks.setClassHook(ClassHooks.AnimableList, cc);
        for (final Object ofield : cc.getNode().fields) {
            final FieldNode field = (FieldNode) ofield;
            System.out.println(field.desc + " vs " + aName);
            if (field.desc.equals("L" + cc.getName() + ";")) {
                hooks.setFieldHook(ClassHooks.AnimableList, FieldHooks.GetNextAnimableNode,
                        new FieldInsnNode(Opcodes.GETFIELD, cc.getName(), field.name, field.desc));
            } else if (field.desc.equals("L" + aName + ";")) {
                hooks.setFieldHook(ClassHooks.AnimableList, FieldHooks.GetCurrentAnimable,
                        new FieldInsnNode(Opcodes.GETFIELD, cc.getName(), field.name, field.desc));
            }
        }
        return HookState.Found;
    }

    @Override
    public AbstractClassHookEnum dependency() {
        return ClassHooks.Animable;
    }
    
    public boolean containsField(final ClassContainer cc, final String desc) {
        for (final Object ofield : cc.getNode().fields) {
            final FieldNode field = (FieldNode) ofield;
            if (field.desc.equals(desc))
                return true;
        }
        return false;
    }

}
